package cn.txun.csmall.gateway.filters;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;
import java.util.List;

/**
 * 网关过滤器必须实现一个接口GlobalFilter
 * 如果想定义多个过滤器执行顺序
 * 还有实现接口Ordered
 */
@Slf4j
@Component
public class MyFilter03 implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
       //chain.filter()调用之前编写的逻辑代码，都属pre时间
        System.out.println("filter03执行了pre");
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //获取请求头
        HttpHeaders headers = request.getHeaders();
        //从headers获取响应的头数据，Host，两种方式
        InetSocketAddress host = headers.getHost();
        List<String> list = headers.get("Host");
        log.info("从api方法getHost获取Host包含IP:{},和端口:{}",host.getHostName(),host.getPort());
        log.info("从api方法get('Host')获取数据：{}",list.get(0));
        Mono<Void> result = chain.filter(exchange);//生成一个继续执行的过滤器后的Mono
        //return Mono.empty();//调用empty()，做阻断
        return result;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
